var interval;
var joystickHold = false;
var joystick;
var times;

function setIntervalKeyDown(key) {
    if (interval) {
        clearInterval(interval);
    }
    onKeyDown(key);
    interval = setInterval(() => {
        onKeyDown(key);
    }, 225);
}

function initJoystick() {
    let position = {
        left: '80%',
        top: '85%'
    };

    var options = {
        zone: document.getElementById('zone'),
        //threshold : 1,
        mode: 'static',
        position: position,
        color: 'white'
            // color: 'url(/assets/imgs/joystick.png)'
    }
    if (joystick) {
        joystick.destroy()
    }
    let modal = 'portrait';
    joystick = nipplejs.create(options);
    joystick.on('dir:up', function(evt, nipple) {
        setIntervalKeyDown(modal == 'portrait' ? 4 : 1)
    }).on('dir:down', function(evt, nipple) {
        setIntervalKeyDown(modal == 'portrait' ? 3 : 2)
    }).on('dir:left', function(evt, nipple) {
        setIntervalKeyDown(modal == 'portrait' ? 1 : 3)
    }).on('dir:right', function(evt, nipple) {
        setIntervalKeyDown(modal == 'portrait' ? 2 : 4)
    }).on('end', function(evt, nipple) {
        console.log('end')
        clearInterval(interval);
    });
}

$(function() {
    lcdRotateMode = 2; // 强制竖屏

    $('#btn_enter').on('tapstart', function(e) {
        $(this).addClass("active");
        onKeyDown(7);
    });

    $('#btn_exit').on('tapstart', function(e) {
        $(this).addClass("active");
        onKeyDown(8);
    });

    $('#btn_up').on('tapstart', function(e) {
        $(this).addClass("active");
        onKeyDown(5);
    });
    $('#btn_down').on('tapstart', function(e) {
        $(this).addClass("active");
        onKeyDown(6);
    });

    $('#btn_enter,#btn_exit,#btn_up,#btn_down').on('tapend', function(e) {
        $(this).removeClass("active");
        e.preventDefault();
    });

    setTimeout(() => {
        $('#btn_enter,#btn_exit,#btn_up,#btn_down').show(100);
        initJoystick()
    }, 100);
});